﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Web.Script.Serialization;

namespace WebeTerm.Common
{
    public static class WebUtility
    {
        /// <summary>
        /// 提示
        /// </summary>
        /// <param name="message">说明</param>
        public static void Alert(Page page, string message)
        {
            message = message.Replace("'", "\\'").Replace("\"", "\\\"");
            string script = "<script type=\"text/javascript\">";
            script += "AlertMessage('" + message + "');";
            script += "</script>";

            page.ClientScript.RegisterStartupScript(page.GetType(), "message", script, false);
        }



        /// <summary>
        /// 获取格式化脚本信息，将引号转义
        /// </summary>
        /// <param name="message">信息</param>
        /// <returns>格式化后的信息</returns>
        public static string FormatScriptMessage(string message)
        {
            return message.Replace("'", "\\'").Replace("\"", "\\\"").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ");
        }

        public static void AlertAndCloseDialog(Page page, string message)
        {
            message = message.Replace("'", "\\'").Replace("\"", "\\\"");
            string script = "<script type=\"text/javascript\">\n";
            script += "$(function(){\n var button={ '确定': function(){Dialog_CloseMessageBox();}};\n";
            script += "var dialogNum = Dialog_ShowMessageBox('" + message + "', '" + message + "', 400, 200, button);\n";
            script += "PartCommander.RegistEventReceiver('Dialog_OnDialogClose_' + dialogNum, CloseDialog);\n});\n";

            script += "function CloseDialog(){\n";
            script += "setTimeout('parent.Dialog_Close()', 10);\n}";
            script += "</script>";

            page.ClientScript.RegisterStartupScript(page.GetType(), "message", script, false);
        }

        public static void AlertAndClose(Page page, string message,string title = null)
        {
            string afterfunction = "RefreshOpener();\nCloseWindow();";
            AlertWithTitle(page, title??message, message, afterfunction);
        }

        public static void Alert(Page page, string message, string afterAlertFunction = null)
        {
            AlertWithTitle(page, message, message, afterAlertFunction);
        }

        public static void AlertWithTitle(Page page,string title, string message, string afterAlertFunction = null)
        {
            string script = "<script type=\"text/javascript\">\n";
            script += "$(function(){\n var button={ '确定': function(){Dialog_CloseMessageBox();}};\n";
            script += "var dialogNum = Dialog_ShowMessageBox('" + title + "', '" + message + "', 400, 200, button);\n";
            script += "PartCommander.RegistEventReceiver('Dialog_OnDialogClose_' + dialogNum, AfterAlertFunction);\n});\n";

            script += "function AfterAlertFunction(){\n";
            if (!String.IsNullOrEmpty(afterAlertFunction))
                script += afterAlertFunction;
            script += "\n}\n";
            script += "</script>";

            page.ClientScript.RegisterStartupScript(page.GetType(), "message", script, false);
        }


        public static void AlertAndRedirect(Page page, string message, string url)
        {
            string script = "<script type=\"text/javascript\">\n";
            script += "$(function(){\n var button={ '确定': function(){Dialog_CloseMessageBox();}};\n";
            script += "var dialogNum = Dialog_ShowMessageBox('" + message + "', '" + message + "', 400, 200, button);\n";
            script += "PartCommander.RegistEventReceiver('Dialog_OnDialogClose_' + dialogNum, PageRedirect);\n});\n";

            script += "function PageRedirect(){\n";
            script += "Redirect('" + page.ResolveUrl(url) + "')\n}";
            script += "</script>";

            page.ClientScript.RegisterStartupScript(page.GetType(), "message", script, false);
        }

        

        public static void ConfirmAndRedirect(Page page, string message, string url,string function = "")
        {
            function = string.IsNullOrEmpty(function) ? string.Format(@"Redirect('{0}')", page.ResolveUrl(url)) : function;
            string script = "<script type=\"text/javascript\">\n";
            script += "$(function(){\n var button={ '确定': function(){Dialog_CloseMessageBox();" + function + ";},'取消':function(){Dialog_CloseMessageBox();}};\n";
            script += "var dialogNum = Dialog_ShowMessageBox('确认信息', '" + message + "', 400, 200, button);\n";
            script += "});</script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), "message", script, false);
        }

        /// <summary>
        /// 提示
        /// </summary>
        /// <param name="message">说明</param>
        public static void JsMethod(Page page, string Method)
        {
            string script = "<script type=\"text/javascript\">";
            script += Method;
            script += "</script>";

            page.ClientScript.RegisterStartupScript(page.GetType(), "JsMethod", script, false);
        }


        public static string CreateNode(string id, string text, string state)
        {
            string node = "\"id\": \"{0}\", \"text\": \"{1}\",\"state\":\"{2}\"";

            return "{" + string.Format(node, id, text, state) + "},";
        }

        public static string CreateNode(string id, string text, string state, string attributes)
        {
            string node = "\"id\": \"{0}\", \"text\": \"{1}\",\"state\":\"{2}\",\"attributes\":{3}";

            return "{" + string.Format(node, id, text, state, attributes) + "},";
        }

        public static void ControlInitValue(Control control, string id, string value)
        {
            Control child = control.FindControl(id);
            if (child is Literal)
                ((Literal)child).Text = value;
            if (child is HtmlInputCheckBox)
                ((HtmlInputCheckBox)child).Checked = bool.Parse(value);
            if (child is HtmlInputHidden)
                ((HtmlInputHidden)child).Value = value;
        }

        /// <summary>
        /// 获取Repeater中控件的值
        /// </summary>
        /// <param name="item">子项</param>
        /// <param name="controlID">控件编号</param>
        /// <returns>Repeater中控件的值</returns>
        public static string GetRptControlValue(RepeaterItem item, string controlID)
        {
            Control control = item.FindControl(controlID);

            if (control is HiddenField)
            {
                return ((HiddenField)control).Value.Trim();
            }
            else if (control is TextBox)
            {
                return ((TextBox)control).Text.Trim();
            }
            else if (control is Label)
            {
                return ((Label)control).Text.Trim();
            }
            else if (control is DropDownList)
            {
                return ((DropDownList)control).Text;
            }
            else if (control is CheckBox)
            {
                return ((CheckBox)control).Checked ? "1" : "0";
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }
        }

        public static int GetCssIndex(int index)
        {
            return 2;
        }

        public static string GetAString(string clickevent, string label)
        {
            return "<a href=\"javascript:void(null);\" onclick=\"" + clickevent + "\">" + label + "</a>";
        }

        public static string GetIsValidString(string valid)
        {
            if (valid == "1" || valid == "True")
                return "有效";
            return "无效";
        }

        /// <summary>
        /// 序列化对象
        /// </summary>
        public static string Serialize<T>(T t)
        {
            JavaScriptSerializer jsser = new JavaScriptSerializer();
            string json = jsser.Serialize(t);
            return json;
        }

        /// <summary>
        /// 将XML反序列化为对象
        /// </summary>
        public static T Deserialize<T>(string json)
        {
            JavaScriptSerializer jsser = new JavaScriptSerializer();
            return jsser.Deserialize<T>(json);
        }

        /// <summary>
        /// 取得虚拟站点绝对根路径
        /// </summary>
        /// <returns></returns>
        public static string GetApplicationRootPath()
        {
            string path = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty) + HttpContext.Current.Request.ApplicationPath;
            return VirtualPathUtility.AppendTrailingSlash(path);
        }


        /// <summary>
        /// 将整个网页导出来Excel
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="FileName"></param>
        public static void ExportData(string strContent, string FileName)
        {
            FileName = FileName + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "gb2312";
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //this.Page.EnableViewState = false; 
            // 添加头信息，为"文件下载/另存为"对话框指定默认文件名 
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");
            // 把文件流发送到客户端 
            HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
            HttpContext.Current.Response.Write(strContent);

            HttpContext.Current.Response.Write("</body></html>");
            // 停止页面的执行 
            //Response.End();
        }
    }
}
